package com.tech.view.common;

import org.jdesktop.swingx.util.GraphicsUtilities;

import java.awt.image.BufferedImage;

/**
 * 图片大小调整器
 * 用于商品详情页图片的有序布局
 */
public class ImageSizeAdjuster {
	// 这三个size都是宽度的枚举值
	public static final int SIZE01 = 200;
	public static final int SIZE02 = 400;
	public static final int SIZE03 = 800;

	/**
	 * 从已有常量中选择一个最接近的大小进行缩放，不过为了图片质量，会尽量让图片进行缩小而不是放大
	 *
	 * @param image 待调整图像
	 * @return 调整后图像，宽度为三个枚举值中的一个
	 */
	public static BufferedImage adjust(BufferedImage image) {
		int w = image.getWidth();
		int h = image.getHeight();
		if (w > SIZE03) {
			return GraphicsUtilities.createThumbnailFast(image, SIZE03, h * SIZE03 / w);
		} else if (w > SIZE02) {
			if ((w - SIZE02) * 1.0f / w - (SIZE03 - w) * 1.0f / w > 0.25f) //放大
				return GraphicsUtil.createScaledCompositeInstance(image, SIZE03, h * SIZE03 / w);
			else //缩小
				return GraphicsUtilities.createThumbnailFast(image, SIZE02, h * SIZE02 / w);
		} else if (w > SIZE01) {
			if ((w - SIZE01) * 1.0f / w - (SIZE02 - w) * 1.0f / w > 0.25f)
				return GraphicsUtil.createScaledCompositeInstance(image, SIZE02, h * SIZE02 / w);
			else
				return GraphicsUtilities.createThumbnailFast(image, SIZE01, h * SIZE01 / w);
		} else { //放大
			return GraphicsUtil.createScaledCompositeInstance(image, SIZE01, h * SIZE01 / w);
		}
	}
}
